<?php

/**
 * 站外能力测评考试
 */

namespace Api\Controller;

use Common\Controller\BaseController;
use Think\Crypt\Driver\Xxtea;
use Think\Exception;

class AbilityCheckController extends BaseController {

    public function _initialize() {
        
    }

    /**
     * 企业能力评测题目，步骤一：获取中级题目
     */
    public function getMiddleQuestionList() {
        $iCateId = $this->getParam('cate_id', 0, 'int+', TRUE);
        empty($iCateId) && $this->error('未选择测评岗位');
        $objAbilityCheckQuestion = new \Common\Model\AbilityCheckQuestionModel();
        $returnList = $objAbilityCheckQuestion->getQuestionList($iCateId, 2);
        $arr['question_list'] = $returnList;
        $arr['question_level'] = 1;
        $this->returnList($arr);
    }

    /**
     * 企业能力评测题目，步骤二：提交中级试题答案并获取高或低级题目
     */
    public function submitMiddleAndGetNextQuestionList() {
        try {
            $this->_checkToken();
            $jsonAnswerListStep1 = $_POST['answer_list_step_1'];
            $arrAnswerListStep1 = json_decode($jsonAnswerListStep1, true);
            list($check_total_score, $total_score, $iCateId) = $this->answerCheckList($arrAnswerListStep1);

            $objAbilityCheckQuestion = new \Common\Model\AbilityCheckQuestionModel();

            if ($check_total_score >= $total_score * 0.8) {
                //高级题列表
                $returnList['question_list'] = $objAbilityCheckQuestion->getQuestionList($iCateId, 3);
                $returnList['question_level'] = 3;
            } else {
                //初级题列表
                $returnList['question_list'] = $objAbilityCheckQuestion->getQuestionList($iCateId, 1);
                $returnList['question_level'] = 1;
            }
        } catch (Exception $exc) {
            $data = array();
            $data['msg'] = $exc->getMessage();
            $data['code'] = $exc->getCode();
            $data['file'] = $exc->getFile();
            $data['line'] = $exc->getLine();
            file_put_contents('errLog.txt', var_export($data,true), FILE_APPEND);
        }
        
        $this->returnList($returnList);
    }

    /**
     * 企业能力测评，步骤三：提交最终试题答案
     * $iQuestionLevel题目级别：1-初级 3-高级
     * $iFinalQuestionLevel最终用户测评结果级别：0-新手 1-初级 2-中级 3-高级
     */
    public function submitAllAnswer() {
        $iCompanyId = $this->_checkToken();
        $iQuestionLevel = $this->getParam('question_level', '', '/^[1|3]$/', true, '参数错误');
        $jsonAnswerListStep1 = $_POST['answer_list_step_1'];
        $jsonAnswerListStep2 = $_POST['answer_list_step_2'];
        $jsonUserInfo = $_POST['user_info'];
        $arrAnswerListStep1 = json_decode($jsonAnswerListStep1, true);
        $arrAnswerListStep2 = json_decode($jsonAnswerListStep2, true);
        $arrUserInfo = json_decode($jsonUserInfo, true);
        if (empty($arrAnswerListStep1) || empty($arrAnswerListStep2) || empty($arrUserInfo)) {
            $this->error('参数错误');
        }
        //检查第二次的提交的答案
        list($check_total_score2, $total_score2, $iCateId) = $this->answerCheckList($arrAnswerListStep2);
        if ($check_total_score2 >= $total_score2 * 0.8) {
            $arrFinalAnswerList = $arrAnswerListStep2;
            $iFinalQuestionLevel = $iQuestionLevel;
        } else {
            if ($iQuestionLevel == 1) {
                $iFinalQuestionLevel = 0;
                $arrFinalAnswerList = $arrAnswerListStep2;
            } else {
                $iFinalQuestionLevel = 2;
                $arrFinalAnswerList = $arrAnswerListStep1;
            }
        }
        list($check_total_score2, $total_score2, $iCateId, $arrFinalAnswerCheckList) = $this->answerCheckList($arrFinalAnswerList);
        D()->startTrans();
        foreach ($arrUserInfo as &$val) {
            // 去除斜杠
            if (get_magic_quotes_gpc()) {
                $val = stripslashes($val);
            }
            $val = htmlspecialchars($val, ENT_QUOTES);
        }
        unset($val);
        //添加新用户
        $iUserId = $this->addUser($arrUserInfo);
        //添加基本信息
        $arrUserInfo['user_id'] = $iUserId;
        $arrUserInfo['read_auth'] = 3;
        $arrUserInfo['cate_id'] = $iCateId;
        $arrUserInfo['company_id'] = $iCompanyId;
        $arrUserInfo['check_level'] = $iFinalQuestionLevel;
        $arrUserInfo['create_time'] = date('Y-m-d H:i:s');
        $objAbilityCheck = M('AbilityCheck');
        $iAbilityCheckId = $objAbilityCheck->add($arrUserInfo);

        //添加最终提交答案
        foreach ($arrFinalAnswerCheckList as &$val) {
            $val['ability_check_id'] = $iAbilityCheckId;
        }
        unset($val);
        $objAbilityCheckAnswer = M('AbilityCheckAnswer');
        $resAnswerList = $objAbilityCheckAnswer->addAll($arrFinalAnswerCheckList);
        if ($iUserId && $iAbilityCheckId && $resAnswerList) {
            D()->commit();
            $this->success('操作成功');
        } else {
            D()->rollback();
            $this->returnList('操作失败');
        }
    }

    //检测提交的token，获取企业ID
    private function  _checkToken() {
        $strToken = $this->getParam('token', '', 'string', TRUE);
        $objXxtea = new Xxtea();
        $iCompanyId = $objXxtea->decrypt(base64_decode($strToken), C('XXTEA_KEY'));
        if (empty($iCompanyId)) {
            $this->error('非法操作');
        }
        return $iCompanyId;
    }

    /**
     * 批量批改答案
     * @param array $arrAnswerList 题目ID+用户答案
     * @return array $check_total_score:批改后得分 $total_score:题目总分 $iCateId:
     */
    private function answerCheckList($arrAnswerList) {
        foreach ($arrAnswerList as $val) {
            $arrQuestionIds[] = $val['ability_check_question_id'];
        }
        if (empty($arrQuestionIds)) {
            $this->error('参数错误');
        }
        $arrTrueAnswerList = M('AbilityCheckQuestion')->field('ability_check_question_id,first_ability_level_id,answer')->where(array('ability_check_question_id' => array('in', $arrQuestionIds)))->select();
        $check_total_score = 0; //实际得分
        $first_ability_level_id = 0;
        foreach ($arrTrueAnswerList as $val) {
            $first_ability_level_id = $val['first_ability_level_id'];
            foreach ($arrAnswerList as &$vv) {
                if ($vv['ability_check_question_id'] == $val['ability_check_question_id']) {
                    if (!empty($vv['s_answer']) && $vv['s_answer'] == $val['answer']) {
                        $check_total_score++;
                        $vv['check_result'] = 1;
                    } else {
                        $vv['check_result'] = 0;
                    }
                }
            }
            unset($vv);
        }
        $iCateId = M('AbilityLevel')->where(array('ability_level_id' => $first_ability_level_id))->getField('cate_id');
        $total_score = count($arrTrueAnswerList);
        return array($check_total_score, $total_score, $iCateId, $arrAnswerList);
    }

    /**
     * 新增新用户
     */
    private function addUser($arrUserInfo) {
        $birthday = $arrUserInfo['birthday'] . '-00';
        $arrData['user_name'] = $arrUserInfo['real_name'];
        $arrData['real_name'] = $arrUserInfo['real_name'];
        $arrData['phone'] = $arrUserInfo['phone'];
        $arrData['sex'] = intval($arrUserInfo['sex']);
        $arrData['birthday'] = $birthday;
        $arrData['password'] = md5('t1x2w3s4');
        $arrData['create_time'] = date('Y-m-d H:i:s');
        $objUser = M('User');
        $iUserId = $objUser->where(array('phone' => $arrUserInfo['phone']))->getField('user_id');
        if (empty($iUserId)) {
            $iUserId = $objUser->add($arrData);
        } else {
            $arrSave['real_name'] = $arrUserInfo['real_name'];
            $arrSave['sex'] = intval($arrUserInfo['sex']);
            $arrSave['birthday'] = $birthday;
            $arrSave['type'] = array('exp', "type|1");
            $objUser->where(array('phone' => $arrUserInfo['phone']))->save($arrSave);
        }
        return $iUserId;
    }

}
